<template>
  <el-container>
    <el-aside>
      <div class="header">个人资料</div>
      <el-image v-if="!headImageFlag" :src="user.headImage" class="avatar" :preview-src-list="srcList"></el-image>
      <el-upload
          class="avatar-uploader"
          action="api/user/updateHeadImage"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :headers="token"
          v-else
      >
        <i class="el-icon-plus avatar-uploader-icon"
           style="height: 120px;width: 120px;background-color:rgba(255,255,255,0.39);margin: 20px 0;"></i>
      </el-upload>
      <span @click="headImageUpdate"
            style="cursor: pointer;color: rgba(147,217,248,0.79);margin-right: 20px">修改头像</span>
      <span v-if="headImageFlag" @click="openMaterial"
            style="cursor: pointer;color: rgba(147,217,248,0.79);position: absolute">素材库</span>
      <el-divider></el-divider>
      <span class="left"><i class="el-icon-user"></i>登录名称</span><span class="right">{{ user.username }}</span><br>
      <el-divider></el-divider>
      <span class="left"><i class="el-icon-phone-outline"></i>手机号</span><span class="right">{{
        user.phone
      }}</span><br>
      <el-divider></el-divider>
      <span class="left"><i class="el-icon-message"></i>邮箱</span><span class="right">{{ user.email }}</span><br>
      <el-divider></el-divider>
      <span class="left"><i class="el-icon-timer"></i>创建时间</span><span class="right">{{
        user.createTime
      }}</span><br>
      <el-divider></el-divider>
    </el-aside>
    <el-main>
      <div class="header2">基本资料</div>
      <el-tabs type="border-card">
        <el-tab-pane label="基本资料">
          <el-form ref="user" :model="form" label-width="80px" :rules="updateFlag ? rules : ''" :key="key">
            <el-form-item label="用户名:">
              <el-input v-model="form.username" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-select v-if="updateFlag" v-model="form.sex" placeholder="性别">
                <el-option label="男" value="1"></el-option>
                <el-option label="女" value="0"></el-option>
                <el-option label="其他" value="2"></el-option>
              </el-select>
              <el-input v-else :disabled="true"
                        :value="form.sex"></el-input>
            </el-form-item>
            <el-form-item label="生日" prop="birthday">
              <el-col :span="11" v-if="updateFlag">
                <el-date-picker type="date" placeholder="选择日期" v-model="form.birthday"
                                style="width: 100%;"></el-date-picker>
              </el-col>
              <el-input v-else v-model="form.birthday" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" :disabled="!updateFlag"></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="phone">
              <el-input v-model="form.phone" :disabled="!updateFlag"></el-input>
            </el-form-item>
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="form.realName" :disabled="!updateFlag"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button :type="updateFlag ? 'primary' : '' " @click="onSubmit">{{
                  updateFlag ? '提交' : '修改个人信息'
                }}
              </el-button>
              <el-button @click="cancel" v-if="updateFlag" style="margin-left: 30px">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="密码修改">
          <el-form ref="user" :model="pwd" label-width="80px" :rules="rules" :key="key">
            <el-form-item label="原密码" prop="old">
              <el-input show-password autocomplete="off" v-model="pwd.old" placeholder="请输入原密码"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="new">
              <el-input show-password autocomplete="off" v-model="pwd.new" placeholder="请输入新密码"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="new2">
              <el-input show-password autocomplete="off" v-model="pwd.new2" placeholder="请确认新密码"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type='primary' @click="submitPassword">修改密码</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <div class="material">
        <el-dialog
            title="素材库"
            :visible.sync="materialDia"
            width="50%"
            :before-close="materialClose">
          <div v-for="img in material" :key="img.url"
               style="display: inline-block;vertical-align: top;margin-top: 20px">
            <div style="display: inline-block;vertical-align: top;width: 80px;height: 80px;margin-right: 10px"  @click="materialClick(img)">
              <el-image
                  style="width: 80px; height: 80px;cursor: pointer"
                  :src="img.url"
                  :key="key"
              />
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="materialDia = false">取 消</el-button>
        </span>
        </el-dialog>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import axios from "@/Axios/axios";

export default {
  data() {
    return {
      user: {},
      form: {},
      pwd: {},
      updateFlag: false,
      headImageFlag: false,
      materialDia: false,
      material: [],
      srcList: [],
      key: Math.random(),
      token: {
        "token": window.sessionStorage.getItem("token"),
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
        ],
        old: [
          {required: true, message: '请输入原密码', trigger: 'blur'},
        ],
        new: [
          {required: true, message: '请输入新密码', trigger: 'blur'},
        ],
        new2: [
          {required: true, message: '请输入确认密码', trigger: 'blur'},
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'change'},
        ],
        birthday: [
          {required: true, message: '请选择生日', trigger: 'change'},
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur'},
        ],
        phone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {min: 11, max: 11, message: '请输入正确的长度为十一位的手机号码', trigger: 'blur'},
          {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur'}
        ],
        realName: [
          {required: true, message: '请输入真实姓名', trigger: 'blur'},
          {
            min: 2,
            max: 10,
            message: '请输入正确的真实姓名格式,长度应在2个字符(或汉字)-10个字符(或汉字)之间',
            trigger: 'blur'
          },
        ],
      },
    }
  },
  mounted() {
    this.getUser();
    this.pwd = '';
  },
  methods: {
    getUser() {
      axios.get("/user/getUser").then(res => {
        if (res.code === 200) {
          this.user = res.data;
          this.user.sex = this.user.sex === 0 ? '女' : this.user.sex === 1 ? '男' : '其他';
          this.form = JSON.parse(JSON.stringify(this.user));
          this.key = Math.random();
          this.srcList.push(this.user.headImage);
        } else {
          this.$message.error(res.msg);
        }
      }).catch(() => {
      })
    },

    handleAvatarSuccess(res) {
      if (res.code !== 200) {
        this.$message.error(res.msg);
      }
      this.$message.success("头像修改成功！");
      this.headImageFlag = false;
      this.getUser();
    },

    beforeAvatarUpload(file) {
      const imageFormats = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'];
      const isImage = imageFormats.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error('上传头像图片只能是图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },

    onSubmit() {
      if (!this.updateFlag) {
        this.updateFlag = true;
        return;
      }
      axios.post("/user/updateUser", this.form).then(res => {
        if (res.code === 200) {
          this.$message.success("修改成功！");
          this.updateFlag = false;
          this.getUser();
          this.key = Math.random();
        } else {
          this.$message.error(res.msg);
        }
      }).catch(() => {
      })
    },
    cancel() {
      this.updateFlag = false;
      this.getUser();
      this.key = Math.random();
    },
    headImageUpdate() {
      this.headImageFlag = !this.headImageFlag;
    },
    submitPassword() {
      if (this.pwd.old === '' || this.pwd.old === null || this.pwd.old === undefined) {
        this.$message.error("请输入原密码");
        return;
      }
      if (this.pwd.new === '' || this.pwd.new === null || this.pwd.new === undefined) {
        this.$message.error("请输入新密码");
        return;
      }
      if (this.pwd.new2 === '' || this.pwd.new2 === null || this.pwd.new2 === undefined) {
        this.$message.error("请输入确认密码");
        return;
      }
      if (this.pwd.new !== this.pwd.new2) {
        this.$message.error("新密码与确认密码不同，请重新确认后再提交！");
        return;
      }
      if (this.pwd.new === this.pwd.old) {
        this.$message.warning("不建议原密码与新密码相同，请更换新密码后重新提交！");
        return;
      }
      this.pwd.id = this.user.id;
      axios.post("/user/updatePassword", this.pwd).then(res => {
        if (res.code === 200) {
          this.$message.success("密码修改成功！");
          this.pwd = {};
        } else {
          this.$message.error(res.msg);
        }
      }).catch(() => {
      })
    },
    materialClose(done) {
      this.materialDia = false;
      this.headImageFlag = false;
      done();
    },
    materialClick(item) {
      if (item.groupId === null) {
        this.$message.error("素材状态异常，请选择其他素材！");
        return;
      }
      let form = {};
      form.id = this.user.id;
      form.groupId = item.groupId;
      axios.post("user/updateHeadImgByMaterial", form).then(res => {
        if (res.code === 200) {
          this.$message.success("头像修改成功！");
          this.key = Math.random();
        }
      }).catch(() => {
      })
      this.headImageFlag = false;
      this.materialDia = false;
      this.getUser();
    },
    openMaterial() {
      let form = {};
      form.status = 1;
      form.type = 1;
      axios.post("materialLibrary/list", form).then(res => {
        if (res.code === 200) {
          this.material = res.data;
          this.materialDia = true;
        } else {
          this.$message.error("素材库为空，请自行上传吧！");
        }
      }).catch(() => {
      })
    },
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border-radius: 50%;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  border-radius: 50%;
  margin: 20px auto;
}

.el-input {
  border-radius: 10px;
  width: 400px;
}

.el-col {
  border-radius: 10px;
  width: 400px;
}

.el-select {
  border-radius: 10px;
  width: 400px;
}

.el-form {
  margin: 20px;
}

.el-form-item {
  margin-right: 120px;
}

.el-aside {
  width: 25% !important; /* 使用百分比宽度 */
  min-width: 250px;
  max-width: 350px;
  height: auto;
}

.el-main {
  flex: 1;
  padding: 20px;
}

.el-input, .el-select {
  width: 100%;
  max-width: 400px;
}

.avatar {
  width: 120px;
  height: 120px;
  max-width: 100%;
  object-fit: cover;
}

body > .el-container {
  height: 100% !important;
  margin: 20px !important;
}

.header {
  background-color: rgba(239, 133, 75, 0.42);
  height: 35px;
  line-height: 35px;
  font-size: 16px;
  text-align: left;
  font-family: cursive;
}

.header2 {
  background-color: rgba(211, 243, 197, 0.98);
  height: 35px;
  line-height: 35px;
  font-size: 16px;
  text-align: left;
  font-family: cursive;
}

.left {
  float: left;
  margin-left: 20px;
  font-family: cursive;
}

.right {
  float: right;
  margin-right: 20px;
  font-size: 14px;
}

.el-divider {
  margin: 12px 0 !important;
}

.el-tabs {

  background-color: rgba(117, 183, 155, 0.2);
}

.el-tabs >>> .is-active {
  background-color: rgba(211, 243, 197, 0.98) !important;
  color: #909399 !important;
}

.el-tabs >>> .el-tabs__nav-scroll {
  background-color: rgba(117, 183, 155, 0.15) !important;
}
</style>